import { defineStore } from 'pinia'
import { allChatroomListApi, chathistoryApi } from '@/api'
import { io, Socket } from "socket.io-client";
import router from '@/router'

import type { ChatRoomInfo } from '@/types/views/group'
import type { HistoryItem } from '@/types/views/chat'
import type { JoinRoomPayload, Reply, SendMessagePayload, Message } from '@/types/stores/chat';
import { useUserStore } from './user'
export const useChatStore = defineStore('chat', () => {
    const chatroomList = ref<(ChatRoomInfo)[]>([])
    const currentChatroom = ref<number>(0)
    const historyPoor = ref<{
        [key: number | string]: HistoryItem[]
    }>({})
    const currentHistory = computed(() => (historyPoor.value[currentChatroom.value] || []))
    async function getChatroomList() {
        const { data } = await allChatroomListApi()
        chatroomList.value = data
    }
    async function getHistory(chatroomId: number) {
        const { data } = await chathistoryApi(chatroomId)
        historyPoor.value[chatroomId] = data
        console.log(data, '聊天记录');
    }
    async function changeChatroom(chat: ChatRoomInfo) {

        currentChatroom.value = chat.id
        nextTick(() => {
            scrollToBottom('chatBox', "instant")
        })
    }


    // websocket
    const socketRef = ref<Socket>();
    function chatSocket() {
        const socket = socketRef.value = io(import.meta.env.VITE_SERVE);
        const msgMethod = {
            sendMessage(reply: Reply) {
                console.log(reply, '返回消息');
                // if (!historyPoor.value[reply.message.chatroomId]) {
                //    await getHistory()
                // }
                // @ts-ignore
                historyPoor.value[reply.message.chatroomId].push(reply.message)
                nextTick(() => {
                    scrollToBottom('chatBox')
                })
            },
            joinRoom(reply: Reply) { }
        }
        socket.on('connect', function () {
            console.log('连接成功');

            const payload: JoinRoomPayload = {
                chatroomId: currentChatroom.value,
                userId: useUserStore().user.id
            }

            socket.emit('joinRoom', payload);

            socket.on('message', (reply: Reply) => {
                msgMethod[reply.type](reply)
            });

        });
    }
    watch(currentChatroom, (newVal, oldVal) => {
        if (!newVal) return;
        if (!historyPoor.value[newVal]) {
            getHistory(newVal)
        }
        socketRef.value?.disconnect()
        chatSocket()
    }, { immediate: true, deep: true })

    function sendMessage(value: string) {
        const payload2: SendMessagePayload = {
            sendUserId: useUserStore().user.id,
            chatroomId: currentChatroom.value,
            message: {
                type: 'text',
                content: value
            }
        }
        console.log(payload2, 'ddfdfdfddd');

        socketRef.value?.emit('sendMessage', payload2);
    }
    function scrollToBottom(id: string, behavior: 'instant' | 'smooth' = 'smooth') {
        let el = document.getElementById(id)
        el?.scrollTo({
            top: el.scrollHeight - el.clientHeight,
            behavior
        });
    }
    return { getChatroomList, chatroomList, getHistory, currentChatroom, currentHistory, changeChatroom, sendMessage }
})
